package com.mes.web.controller.tdd;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.google.gson.Gson;
import com.mes.entity.tdd.Department;
import com.mes.entity.tdd.Staff;
import com.mes.entity.tdd.tj.Tpage;
import com.mes.service.tdd.DepartmentService;
import com.mes.service.tdd.StaffService;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ExcelUtils;
import com.mes.utils.MD5;
import com.mes.utils.ResponseUtil;
import com.mes.utils.StringUtil;

/**
 * 
 * @ClassName:StaffController
 * @Description:员工信息
 * @Author tdd
 * @Date 2018年3月22日上午11:22:24
 * @version 1.0
 */
@Controller
@RequestMapping("/staff")
public class StaffController {
	//引入员工的service
	@Resource public StaffService staffService;
	//引入部门的service
	@Resource public DepartmentService departmentService;
	/**
	 * 员工分页列表查询
	 * @param pageBean 分页+条数
	 * @param limit 每页条数
	 * @param offset 条数
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/list")
	public void materieDemandList(HttpServletRequest request,Tpage pageBean,@RequestParam(value="limit",required=false)String limit,@RequestParam(value="offset",required=false)String offset,HttpServletResponse response) throws Exception {
		/*String staffname = request.getParameter("staffname"); 
		if(null != staffname && !staffname.equals("")){
			staffname = new String(staffname.getBytes("iso8859-1"),"utf-8");
			pageBean.setStaffname(staffname);
		}
		String sex = request.getParameter("sex"); 
		if(null != sex && !sex.equals("")){
			sex = new String(sex.getBytes("iso8859-1"),"utf-8");
			pageBean.setSex(sex);;
		}*/
		//页数
		pageBean.setPage(Integer.parseInt(offset)/Integer.parseInt(limit));
		//每页条数
		pageBean.setPageSize(Integer.parseInt(limit));
		//是否删除：未删除
		pageBean.setIsdelete("0");
		//员工分页列表查询
		List<Staff> staffs=staffService.list(pageBean);
		//员工总条数
		int total=staffService.total(pageBean);
		//员工分页列表查询 和总条数传递到jsp
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(staffs, jsonConfig);
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}
	/**
	 * 添加员工信息
	 * @param response response对象
	 * @param staff 员工
	 * @param request request对象
	 * @throws IOException IO流异常
	 */
	@RequestMapping("/add")
	public void add(HttpServletResponse response,Staff staff,HttpServletRequest request) throws IOException{
		//判断session
        HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        Staff userSession = (Staff) session.getAttribute("staff");
        //当前时间
        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        String   date   =   sDateFormat.format(new Date());
        //根据编号查所有
        Tpage pageBean = new Tpage();
        pageBean.setStaffnumbering(staff.getStaffnumbering());
        pageBean.setIsdelete("0");
        List<Staff> total = staffService.all(pageBean);
    	//判断编号是否重复
		//编号重复
		if (total.size()>0) {
			response.getWriter().print("-1");
		//编号不重复
		}else{
        	//添加库区
        	//录入人
        	staff.setStenter(userSession.getStaffname());
			if (null != staff.getPasswords() && !staff.getPasswords().equals("")) {
				staff.setPasswords(MD5.md5Encode(staff.getPasswords()));
			}
        	//录入时间
        	staff.setStentertime(date);
        	//是否删除标识，未删除
        	staff.setIsdelete("0");
        	//添加
        	Long id = staffService.add(staff);
        	//添加成功
        	if (null != id && id >= 1) {
        		response.getWriter().print("1");
        		//未成功
        	} else {
        		response.getWriter().print("0");
        	}
		}
	}
	/**
	 * 到修改
	 * @param request request对象
	 * @param response response对象
	 * @return null
	 * @throws Exception 异常
	 */
	@RequestMapping("/toupdate")
	public String toupdata(HttpServletRequest request,HttpServletResponse response) throws Exception{
		//json
		Gson gson=new Gson();
		//根据id查询数据
		Tpage pageBean = new Tpage();
		//获取id
		pageBean.setStaffid(Long.valueOf((Integer.parseInt(request.getParameter("staffid")))));
		//未删除
		pageBean.setIsdelete("0");
		List<Staff> list = staffService.all(pageBean);
		//获得数据
		if (list.size()>0) {
			//传递数据到页面
			ResponseUtil.write(response, gson.toJson(list.get(0)));
		}
		//跳转到修改页面
		return null;
	}
	/**
	 * 修改
	 * @param staff 员工
	 * @param response response对象
	 * @param request request对象
	 * @throws IOException IO流异常
	 */
	@RequestMapping("/update")
	public void updata(Staff staff,HttpServletResponse response,HttpServletRequest request) throws IOException{
		//判断session
		HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        Staff userSession = (Staff) session.getAttribute("staff");
        //当前时间
        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        String   date   =   sDateFormat.format(new Date());
		//修改
        //录入人
    	staff.setStenter(userSession.getStaffname());
    	//录入时间
    	staff.setStentertime(date);
    	//是否删除标识，未删除
    	staff.setIsdelete("0");
		
		//根据id查数据
        //修改前数据
    	Tpage pageBean = new Tpage();
		//获取id
		pageBean.setStaffid(staff.getStaffid());
		//未删除
		pageBean.setIsdelete("0");
		List<Staff> list = staffService.all(pageBean);
		//如果有该条数据
		if (list.size()>0) {
			//根据编号查员工
	        Tpage page = new Tpage();
	        page.setStaffnumbering(staff.getStaffnumbering());
	        page.setIsdelete("0");
			List<Staff> staffs = staffService.all(page);
	    	//判断编号是否重复
			int num = 0;
			//编号重复
	        for (int i = 0; i < staffs.size(); i++) {
	        	//判断编号是否重复
				if (staff.getStaffnumbering().equals(staffs.get(i).getStaffnumbering()) && !list.get(0).getStaffnumbering().equals(staffs.get(i).getStaffnumbering())) {
					num++;
				}
			}
	      //编号不重复
	        if (num <= 0) {
	        	if (null != staff.getPasswords() && !staff.getPasswords().equals("")) {
					staff.setPasswords(MD5.md5Encode(staff.getPasswords()));
				}else{
					staff.setPasswords(list.get(0).getPasswords());
				}
	        	//修改
				int n = staffService.updata(staff);
				//修改成功
				if (n >= 1) {
					response.getWriter().print("1");
					//未成功
				} else {
					response.getWriter().print("0");
				}
			}else {
				//编号重复
				response.getWriter().print("-1");
			}
		//如果没有该条数据(没有)
		}else {
			//该数据不存在
			response.getWriter().print("2");
		}
	}
	/**
	 * 删除
	 * @param ids 员工id用","拼接而成的字符串
	 * @param request request对象
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletRequest request,HttpServletResponse response) throws Exception{
		//判断session
        /*HttpSession session  = request.getSession();
        //从session中取出用户身份信息
        Staff userSession = (Staff) session.getAttribute("staff");*/
        //当前时间
        SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        String   date   =   sDateFormat.format(new Date());
        List<Long> listId = StringUtil.splitListL(ids, ",");
        for (int i = 0; i < listId.size(); i++) {
        	//根据id查数据
        	//修改前数据
        	Tpage pageBean = new Tpage();
        	//获取id
        	pageBean.setStaffid(listId.get(i));
        	//未删除
        	pageBean.setIsdelete("0");
        	List<Staff> list = staffService.all(pageBean);
        	//如果有该条数据
        	if (list.size()>0) {
        		Staff staff = list.get(0);
        		//录入人
		    	/*staff.setStenter(userSession.getStaffname());*/
		    	//录入时间
		    	staff.setStentertime(date);
        		//是否删除指定删除
        		staff.setIsdelete("1");
        		//删除（假删除）
        		int n = staffService.updatadelete(staff);
        		//删除成功
        		if (n >= 1) {
        			//如果该用户正在登录
        			/*if (staff.getStaffid() == userSession.getStaffid()) {
        				//session销毁
        				session.invalidate();
        			}*/
        			/*response.getWriter().print("1");*/
        			//未成功
        		} else {
        			response.getWriter().print("0");
        		}
        		//如果没有该条数据(没有)
        	}else {
        		//该数据不存在
        		response.getWriter().print("2");
        	}
		}
        response.getWriter().print("1");
	}	
	
	
	
	
	
	/**
	 * 导出模板
	 * @param request request对象
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/doExportFile")
	public void doExportFile(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ExcelUtils.exportFile("员工导入模板",names(), response);
	}	
	
	/**
	 * 导出当前页数据
	 * @param pageBean 条件+分页
	 * @param limit 每页行数
	 * @param offset 条数
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/doExport")
	public void doExport(Tpage pageBean,@RequestParam(value="limit",required=false)String limit,@RequestParam(value="offset",required=false)String offset,HttpServletResponse response) throws Exception {
		//页数
		pageBean.setPage(Integer.parseInt(offset)/Integer.parseInt(limit));
		//每页条数
		pageBean.setPageSize(Integer.parseInt(limit));
		//未删除
		pageBean.setIsdelete("0");
		List<Staff> staffs=staffService.list(pageBean);
		List<List<String>> lists = staffzhuanlist(staffs);
		ExcelUtils.export("员工当前数据",namess(), response,lists );
	}	
	/**
	 * 导出所有数据
	 * @param pageBean 条件+分页
	 * @param request request对象
	 * @param response response对象
	 * @throws Exception 异常
	 */
	@RequestMapping("/doExportall")
	public void doExportall(Tpage pageBean,HttpServletRequest request,HttpServletResponse response) throws Exception{
		//未删除
		pageBean.setIsdelete("0");
		List<Staff> staffs=staffService.all(pageBean);
		List<List<String>> lists = staffzhuanlist(staffs);
		ExcelUtils.export("员工所有数据",namess(), response,lists);
	}	
	
	
	/**
	 * 导入
	 * @param file 导入的Excel文件
	 * @param request request对象
	 * @param response response对象
	 * @throws URISyntaxException 检查异常抛出以指示字符串无法解析为URI引用。
	 * @throws IOException IO流异常
	 */
	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException{
		   String savePath = ((HttpSession) request).getServletContext().getRealPath("/WEB-INF/"+file.getOriginalFilename());
		   File newFile=new File(savePath);
		   //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	       file.transferTo(newFile);
	       //取文件后缀
	       String subfix = savePath.lastIndexOf(".")==-1? "" : savePath.substring(savePath.lastIndexOf(".")+1);
	       System.out.println(subfix);
	       List<List<String>> lists = new ArrayList<>();
	       //获取导入行数
	       List<String> names = names();
	       int num = names.size();
	       String xls = "xls";
	       String xlsx = "xlsx";
	       if(xls.equals(subfix)){
	    	   lists = ExcelUtils.readXls(savePath, request,num);
	 	   }else if(xlsx.equals(subfix)){
	 		   lists = ExcelUtils.readXlsx(savePath, request,num);
	 	   }else{
	 	   		response.getWriter().print("0");
	 	   }
	       
	       /*HttpSession session  = request.getSession();
	        //从session中取出用户身份信息
	       Staff userSession = (Staff) session.getAttribute("staff");*/
	       String staffname = null;
	       SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
	       String   date   =   sDateFormat.format(new Date());
	       int count = 0;
	       int flag = 1; 
	       for (int i = 0; i < lists.size(); i++) {
	    	   List<String> list = new ArrayList<>();
	    	   list= lists.get(i);
	    
	    	   Staff staff = new Staff();
	    	   staff.setStaffnumbering(list.get(0));
	    	   staff.setStaffname(list.get(1));
	    	   if("女".equals(list.get(2))){
	    		   staff.setSex("女");
	    	   }else{
	    		   staff.setSex("男");
	    	   }
	    	   staff.setPhone(list.get(3));
	    	   
	    	   //根据部门名称查id
	    	   Tpage pageBean = new Tpage();
	    	   pageBean.setDepartmentname(list.get(4));;
	    	   pageBean.setIsdelete("0");
	   		   List<Department> departments=departmentService.all(pageBean);
	    	   if (departments.size() == 1) {
	    		   staff.setDepartmentid(departments.get(0).getDepartmentid());
	    	   }else{
	    		   break;
	    	   }
	    	   
	    	   if("总经理".equals(list.get(5)) || "副总经理".equals(list.get(5)) || "经理".equals(list.get(5)) || "厂长".equals(list.get(5)) || "主管".equals(list.get(5)) || "员工".equals(list.get(5))){
	    		   staff.setStremark1(list.get(5));
	    		   staff.setStremark2(null);
	    	   }else if("库管".equals(list.get(5)) || "车间操作员".equals(list.get(5))){
	    		   staff.setStremark1(list.get(5));
	    		   if("白班".equals(list.get(6)) || "晚班".equals(list.get(6))){
	    			   staff.setStremark2(list.get(6));
	    		   }else{
	    			   staff.setStremark2("白班");
	    		   }
	    	   }else{
	    		   staff.setStremark1("员工");
	    		   staff.setStremark2(null);
	    	   }
	    	   staff.setDuty(list.get(7));
	    	   staff.setRsdate(list.get(8));
	    	   int ff = addStaff(staff, request, date, staffname);
	    	   staff = null;
	    	   if (ff == 0) {
	    		   flag = 0;
	    		   break;
	    	   }
	    	   count ++;
	       }
	       if(count == 0){
	    	   flag = -1;
	       }
	       response.getWriter().print(flag);
	 }
	/**
	 * 导出模板的表头
	 * @return 导出模板的表头
	 */
	public List<String> names(){
		List<String> list = new ArrayList<>();
		list.add("员工编号");
		list.add("员工姓名");
		list.add("性别");
		list.add("电话");
		list.add("部门");
		list.add("职位");
		list.add("班组");
		list.add("职责");
		list.add("入社日期");
		return list;
	}
	/**
	 * 导出数据表头
	 * @return 导出数据表头
	 */
	public List<String> namess(){
		List<String> list = new ArrayList<>();
		list.add("员工编号");
		list.add("员工姓名");
		list.add("性别");
		list.add("电话");
		list.add("部门");
		list.add("职位");
		list.add("班组");
		list.add("职责");
		list.add("入社日期");
		list.add("录入人");
		list.add("录入时间");
		return list;
	}
	/**
	 * 根据导出数据表头把List<Staff>转List<List<String>>
	 * @param staffs 员工集合
	 * @return 字符串双集合
	 */
	public List<List<String>> staffzhuanlist (List<Staff> staffs){
		List<List<String>> lists = new ArrayList<>();
		for (Staff staff : staffs) {
			List<String> list = new ArrayList<>();
			list.add(staff.getStaffnumbering());
			list.add(staff.getStaffname());
			list.add(staff.getSex());
			list.add(staff.getPhone());
			
			if (null != staff.getDepartment()) {
				list.add(staff.getDepartment().getDepartmentname());
			}else{
				list.add(null);
			}
			
			list.add(staff.getStremark1());
			list.add(staff.getStremark2());
			list.add(staff.getDuty());
			list.add(staff.getRsdate());
			list.add(staff.getStenter());
			list.add(staff.getStentertime());
			lists.add(list);
			list = null;
		}
		return lists;
	}
	/**
	 * 导入数据是的添加方法（如果不满足添加条件，直接过滤）
	 * @param staff 员工
	 * @param request request对象
	 * @param date 当前时间
	 * @param staffname 录入人
	 * @return 是否添加成功标识
	 */
	public int addStaff(Staff staff,
			HttpServletRequest request,String date,String staffname){
		int flag = 0;
        
        //根据编号查员工个数
        Tpage pageBean = new Tpage();
        pageBean.setStaffnumbering(staff.getStaffnumbering());
        pageBean.setIsdelete("0");
        List<Staff> total = staffService.all(pageBean);
    	//根据编号查出员工个数是否大于0判断编号是否重复
		//编号查出员工个数大于0编号重复
		if (total.size()>0) {
			flag = 1;
		//编号不重复
		}else{
        	//添加库区
        	//录入人
        	/*staff.setStenter(staffname);*/
        	//录入时间
        	staff.setStentertime(date);
        	//是否删除标识，未删除
        	staff.setIsdelete("0");
        	//添加
        	Long id = staffService.add(staff);
        	//添加成功
        	if (null != id && id >= 1) {
        		flag = 1;
        		//未成功
        	} else {
        		flag = 0;
        	}
		}
		return flag;
	}
}
